package com.demo.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;

import com.jfinal.kit.PathKit;

public class ExcelUtil {

	public static void export(List<String> titles, List<List> rows, String excelName) throws IOException {
		
		File file = new File(PathKit.getWebRootPath()+"/download" + File.separatorChar + excelName);
		FileInputStream excelFileInputStream = new FileInputStream(file);
		HSSFWorkbook workbook = new HSSFWorkbook(excelFileInputStream);
		excelFileInputStream.close();
		HSSFSheet sheet = workbook.getSheetAt(0);
		
		for(int i = 0 ; i<=sheet.getLastRowNum();i++){
			sheet.createRow(i);
		}
		
		HSSFRow titleRow = sheet.createRow(0);
		titleRow.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("序号");
		for(int i = 0 ; i<titles.size();i++){
			titleRow.createCell(i+1,Cell.CELL_TYPE_STRING).setCellValue(titles.get(i));
		}
		
		for(int i = 0 ; i<rows.size();i++){
			HSSFRow contentRow = sheet.createRow(i+1);
			List<String> row = rows.get(i);
			
			contentRow.createCell(0,Cell.CELL_TYPE_STRING).setCellValue(i+1);
			for(int j = 0 ; j <row.size();j++){
				contentRow.createCell(j+1,Cell.CELL_TYPE_STRING).setCellValue(row.get(j));
			}
		}
		
		FileOutputStream excelFileOutPutStream = new FileOutputStream(file);
		workbook.write(excelFileOutPutStream);
		excelFileOutPutStream.flush();
		// 使用后，及时关闭这个输出流对象， 好习惯，再强调一遍！
		excelFileOutPutStream.close();
	}
	
	

	
}
